package com.yunma.dialog;

import com.common.util.RequestUtil;
import com.common.util.WindowUtil;
import com.string.widget.util.ValueWidget;
import com.swing.dialog.GenericPanel;
import com.swing.dialog.toast.ToastMessage;
import com.swing.menu.MenuUtil2;
import com.yunma.autotest.AutoTestPanel;
import com.yunma.component.MemoAssistPopupTextArea;
import com.yunma.component.ParameterPanel;
import com.yunma.listen.HttpHeaderPanelPopupListener;
import com.yunma.util.TableUtil;
import org.apache.commons.collections.map.ListOrderedMap;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.MouseInputAdapter;
import javax.swing.event.MouseInputListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

public class HttpHeadPanel extends GenericPanel {

    private JPanel contentPanel = new JPanel();
    private AutoTestPanel autoTestPanel;
    private MemoAssistPopupTextArea cookieTextArea;
    private JPanel headerParamPanel;
    private java.util.List<ParameterPanel> parameterPanels = new ArrayList();

    /**
     * Create the dialog.
     */
    public HttpHeadPanel(ListOrderedMap headerParameters) {
//		getContentPane().setLayout(new BorderLayout());
        contentPanel = this;
        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
//		.add(contentPanel, BorderLayout.CENTER);
        contentPanel.setLayout(new BorderLayout(0, 0));
        JSplitPane splitPane = new JSplitPane();
        contentPanel.add(splitPane);
        JPanel headerPanel = new JPanel();
        splitPane.setRightComponent(headerPanel);
        splitPane.setDividerLocation(400);
        headerPanel.setLayout(new BorderLayout(0, 0));
        headerParamPanel = new JPanel();
        headerParamPanel.setLayout(new GridLayout(5, 1, 5, 0));
        if (ValueWidget.isNullOrEmpty(headerParameters)) {
            ParameterPanel panel_2 = new ParameterPanel();
            panel_2.layout2();
            parameterPanels.add(panel_2);
            headerParamPanel.add(panel_2);
        } else {
            initHeader(headerParameters);
        }
        JScrollPane headerscroll = new JScrollPane(headerParamPanel);
        headerPanel.add(headerscroll, BorderLayout.CENTER);
        JPanel panel2 = new JPanel();
        headerPanel.add(panel2, BorderLayout.SOUTH);
        JButton addRowbutton = new JButton("添加一行");
        panel2.add(addRowbutton);
        addRowbutton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("添加一行");
                String sysClipboardText = WindowUtil.getSysClipboardText();
                String key = null;
                String val = null;
                if (!ValueWidget.isNullOrEmpty(sysClipboardText)) {
                    String[] keyVal = sysClipboardText.split("[:=\\s]+", 2);
                    key = keyVal[0].trim();
                    if (keyVal.length > 1) {
                        val = keyVal[1];
                    }
                }

                ParameterPanel panel_3222 = new ParameterPanel(key, val);
                panel_3222.layout2();

                headerParamPanel.add(panel_3222);
                parameterPanels.add(panel_3222);
//                addOptionalParameterPanel(panel_3222, panel_1);
// panel_1.repaint();
                headerParamPanel.updateUI();
            }
        });

        JButton pasteButton = new JButton("黏贴");
        pasteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String requestBodyData = WindowUtil.getSysClipboardText();
                if (requestBodyData.contains(":") && (!requestBodyData.contains("="))) {
                    //兼容 -H 'Host: clientacce.2222.cn'
                    String[] keyVal = requestBodyData.split(":");
                    TableUtil.initParameterPanel(keyVal[0].trim(), keyVal[1].trim(), headerParamPanel, parameterPanels, getMouseInputListener());
                } else {
                    Map requestMap = new TreeMap();
                    RequestUtil.setArgumentMap(requestMap, requestBodyData, true, null, null, false, false);
                    if (ValueWidget.isNullOrEmpty(requestMap)) {
                        ToastMessage.toast("操作失败,因为query string为:" + requestBodyData, 2000, Color.red);
                        return;
                    }
                    TableUtil.initParameterPanel(requestMap, headerParamPanel, parameterPanels, getMouseInputListener());
                }
            }
        });
        panel2.add(pasteButton);

        JPanel panel_22 = new JPanel();
        panel_22.setLayout(new BorderLayout());
        splitPane.setLeftComponent(panel_22);
        cookieTextArea = new MemoAssistPopupTextArea(autoTestPanel);
        cookieTextArea.placeHolder("型如\"CIC=7b84db5d34514b09bf260ed\"");
        JScrollPane scrollPane_3 = new JScrollPane(cookieTextArea);
        Border border1 = BorderFactory.createEtchedBorder(Color.white,
                new Color(148, 145, 140));
        TitledBorder openFileTitle = new TitledBorder(border1, "请求cookie");
        scrollPane_3.setBorder(openFileTitle);

        panel_22.add(scrollPane_3);
        headerParamPanel.addMouseListener(getMouseInputListener());
        headerPanel.addMouseListener(getMouseInputListener());
    }

    /**
     * 点击"请求头",cookie文本框聚焦
     */
    public void focus() {
        if (ValueWidget.isNullOrEmpty(cookieTextArea.getText2())) {
            String clipText = WindowUtil.getSysClipboardText();
            if (clipText.contains("=") && (!clipText.startsWith("{"))
                /* && (clipText.contains("cid") || clipText.contains("JSESSIONID"))*/) {
                cookieTextArea.setText(clipText);
            }

        }
        cookieTextArea.requestFocus();
    }

    public MouseInputListener getMouseInputListener() {
        return new MouseInputAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
//                System.out.println("mouseClicked");
            }

            @Override
            public void mousePressed(MouseEvent e) {
//                super.mousePressed(e);
                MenuUtil2.processEvent(e, headerParamPanel);
//                System.out.println("mouseClicked");
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                super.mouseReleased(e);
//                System.out.println("mouseReleased");

                if (e.getButton() == MouseEvent.BUTTON3) {// right click
                    System.out.println("right click");
                    HttpHeaderPanelPopupListener httpHeaderPanelPopupListener = new HttpHeaderPanelPopupListener(HttpHeadPanel.this, e);
                    JPopupMenu popupmenu = new JPopupMenu();
                    JMenuItem runM = new JMenuItem(MenuUtil2.ACTION_STR_CLEANUP);
                    popupmenu.add(runM);
                    runM.addActionListener(httpHeaderPanelPopupListener);

                    JMenuItem pasteHeaderM = new JMenuItem("黏贴header");
                    popupmenu.add(pasteHeaderM);
                    pasteHeaderM.addActionListener(httpHeaderPanelPopupListener);

                    JMenuItem copyHeaderM = new JMenuItem("复制header");
                    popupmenu.add(copyHeaderM);
                    copyHeaderM.addActionListener(httpHeaderPanelPopupListener);

                    JMenuItem deleteOneHeaderM = new JMenuItem("删除这行");
                    popupmenu.add(deleteOneHeaderM);
                    deleteOneHeaderM.addActionListener(httpHeaderPanelPopupListener);

//                    JMenuItem copyParameterM = new JMenuItem(b);
//                    JMenuItem copyResponseM = new JMenuItem(ACTION_COMMAND_COPY_RESPONSE);
                    popupmenu.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        };
    }

    public void deleteOneRow(ParameterPanel panel_3222) {
        if (null != parameterPanels) {
            headerParamPanel.remove(panel_3222);
            parameterPanels.remove(panel_3222);
            headerParamPanel.updateUI();
        }
    }

    /***
     * 获取请求头参数
     * @return
     */
    public ListOrderedMap getHeaderMap() {
        ListOrderedMap parameters = TableUtil.getParameterOrderedMap(parameterPanels, false);
        return parameters;
    }

    public String getRequestCookies() {
        return cookieTextArea.getText2();
    }

    public void setRequestCookies(String cookies) {
        cookieTextArea.setText(cookies);
    }

    public void initHeader(Map headerParameters) {
        TableUtil.initParameterPanel(headerParameters, headerParamPanel, parameterPanels, getMouseInputListener());
    }

    /***
     * 复制请求头header
     */
    public void copyHeader() {
        ListOrderedMap parameters = getHeaderMap();
        String postData = ValueWidget.getRequestBodyFromMap(parameters, false);
        if (!ValueWidget.isNullOrEmpty(postData)) {
            WindowUtil.setSysClipboardText(postData);
        }
    }

    /***
     * 黏贴请求头header
     */
    public void pasteHeader() {
        String header = WindowUtil.getSysClipboardText();
        if (!ValueWidget.isNullOrEmpty(header)) {
            Map headerMap = new TreeMap();
            RequestUtil.setArgumentMap(headerMap, header, true, null, null, false, false/*quoteEscape*/);
            initHeader(headerMap);
        }
    }

    public java.util.List<ParameterPanel> getParameterPanels() {
        return parameterPanels;
    }
}
